package cn.iocoder.yudao.module.def.controller.admin.project;

import cn.iocoder.yudao.framework.common.util.http.HttpUtils;
import cn.iocoder.yudao.module.def.controller.admin.project.vo.excel.QlVo;
import cn.iocoder.yudao.module.def.controller.admin.project.vo.excel.ZqdlVo;
import cn.iocoder.yudao.module.def.controller.admin.project.vo.excel.ZqmtVo;
import cn.iocoder.yudao.module.def.controller.admin.projectprogress.vo.ProjectProgressRespVO;
import cn.iocoder.yudao.module.def.dal.dataobject.projectprogress.ProjectProgressDO;
import cn.iocoder.yudao.module.def.service.code.CodeService;
import cn.iocoder.yudao.module.def.service.projectprogress.ProjectProgressService;
import cn.iocoder.yudao.module.def.utils.RoadNameProcessorUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import io.swagger.v3.oas.annotations.Parameters;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.web.bind.annotation.*;

import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;


import java.lang.reflect.Field;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.io.IOException;
import java.util.function.Function;
import java.util.stream.Collectors;

import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.*;

import cn.iocoder.yudao.module.def.controller.admin.project.vo.*;
import cn.iocoder.yudao.module.def.dal.dataobject.project.ProjectDO;
import cn.iocoder.yudao.module.def.service.project.ProjectService;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.annotation.security.PermitAll;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

@Tag(name = "管理后台 - 工程")
@RestController
@RequestMapping("/def/project")
@Validated
@Slf4j
public class ProjectController {

    @Resource
    private ProjectService projectService;

    @Resource
    private ProjectProgressService projectProgressService;

    @Resource
    private CodeService codeService;
    @PostMapping("/create")
    @Operation(summary = "创建工程")
    @PreAuthorize("@ss.hasPermission('def:project:create')")
    public CommonResult<Integer> createProject(@Valid @RequestBody ProjectSaveReqVO createReqVO) {
        return success(projectService.createProject(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新工程")
    @PreAuthorize("@ss.hasPermission('def:project:update')")
    public CommonResult<Boolean> updateProject(@Valid @RequestBody ProjectSaveReqVO updateReqVO) {
        projectService.updateProject(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除工程")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('def:project:delete')")
    public CommonResult<Boolean> deleteProject(@RequestParam("id") Integer id) {
        projectService.deleteProject(id);
        return success(true);
    }

    @DeleteMapping("/deleteBatch")
    @Operation(summary = "批量删除工程")
    @Parameter(name = "ids", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('def:project:delete')")
    public CommonResult<Boolean> deleteBatch(@RequestParam("ids") List<Integer> ids) {
        projectService.deleteBatch(ids);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得工程")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('def:project:query')")
    public CommonResult<ProjectRespVO> getProject(@RequestParam("id") Integer id) {
        ProjectDO project = projectService.getProject(id);
        ProjectRespVO projectRespVO = BeanUtils.toBean(project, ProjectRespVO.class);
        ProjectProgressDO projectProgress = projectProgressService.getProjectProgress(project.getId());
        ProjectProgressRespVO progressRespVO = BeanUtils.toBean(projectProgress, ProjectProgressRespVO.class);
        projectRespVO.setProjectProgress(progressRespVO);
        try {
            projectRespVO.setImgs(JSONArray.parseArray(project.getImgs(), String.class));
            projectRespVO.setVideos(JSONArray.parseArray(project.getVideos(), String.class));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return success(projectRespVO);
    }

    @GetMapping("/list")
    @Operation(summary = "获得工程列表")
    @PermitAll
    public CommonResult<List<ProjectRespVO>> getProjectList(@Valid ProjectPageReqVO pageReqVO) {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<ProjectDO> list = projectService.getProjectPage(pageReqVO).getList();
        return success(BeanUtils.toBean(list, ProjectRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得工程分页")
    @PreAuthorize("@ss.hasPermission('def:project:query')")
    public CommonResult<PageResult<ProjectRespVO>> getProjectPage(@Valid ProjectPageReqVO pageReqVO) {
        PageResult<ProjectDO> pageResult = projectService.getProjectPage(pageReqVO);
        pageResult.getList().forEach(project -> {}
        );
        PageResult<ProjectRespVO> projectRespVOPageResult = BeanUtils.toBean(pageResult, ProjectRespVO.class);
        projectRespVOPageResult.getList().forEach(projectRespVO -> {
            ProjectProgressDO projectProgress = projectProgressService.getProjectProgressByPid(projectRespVO.getId());
            projectRespVO.setActualFacilityName(RoadNameProcessorUtil.removeKilometerPart(projectRespVO.getActualFacilityName()));
            projectRespVO.setProjectProgress(BeanUtils.toBean(projectProgress, ProjectProgressRespVO.class));
            projectRespVO.setProjectCateName(codeService.getCodeName(projectRespVO.getProjectCate()));
        });
        return success(projectRespVOPageResult);
    }


    /*    public void exportProjectExcel(@Valid ProjectPageReqVO pageReqVO,
                  HttpServletResponse response) throws IOException {
    *//*        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<ProjectDO> list = projectService.getProjectPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "工程.xls", "数据", ProjectRespVO.class,
                        BeanUtils.toBean(list, ProjectRespVO.class));*//*
        List<ProjectRespVO> projectList = projectService.getProjectList(pageReqVO);
        Map<String, List<ProjectRespVO>> sheetDataMap = projectList.stream()
                .filter(project -> StringUtils.isNotBlank(project.getCodeTxt()))
                .collect(Collectors.groupingBy(ProjectRespVO::getCodeTxt));
        sheetDataMap.forEach((key, value) -> {
            if (Objects.equals("zqdl", key)){
                List<ZqdlVo> zqdlList = new ArrayList<>();
                value.forEach(projectRespVO -> {
                    String otherExtends = projectRespVO.getOtherExtends();
                    projectRespVO.setProjectCateName(codeService.getCodeName(projectRespVO.getProjectCate()));
                    Class<ZqdlVo> zqdlVoClass = dealExtends(otherExtends, ZqdlVo.class);
                    BeanUtils.copyProperties(zqdlVoClass, projectRespVO);
                    zqdlList.add(zqdlVoClass);

                });
            }
        });
        writeMultipleSheets(response, "工程.xlsx", sheetDataMap, ProjectRespVO.class);

    }

    public static <T> Class<T> dealExtends(String jsonArrayString, Class<T> clazz) {
//        String jsonArrayString = "[{\"code_id\":25,\"code_txt\":\"roadType\",\"code_val\":\"车行\"},{\"code_id\":26,\"code_txt\":\"roadCategory\",\"code_val\":\"纵向巡逻路\"}]";

        // 将 JSON 字符串解析为 JSONArray
        JSONArray jsonArray = JSON.parseArray(jsonArrayString);

        // 遍历 JSON 数组并设置 class 对象的属性
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            String codeTxt = jsonObject.getString("code_txt");
            String codeVal = jsonObject.getString("code_val");

            // 使用反射设置属性
            setField(clazz, codeTxt, codeVal);
        }
        return clazz;
    }

    private static <T> void setField(Class<T> clazz, String fieldName, String fieldValue) {
        try {
            Field field = clazz.getDeclaredField(fieldName);
            field.setAccessible(true);
            field.set(clazz, fieldValue);
        } catch (NoSuchFieldException | IllegalAccessException e) {
            // 如果字段不存在，可以选择忽略或抛出异常
            System.out.println("Field " + fieldName + " not found in ZqdlVo class.");
        }
    }*/
    @GetMapping("/export-excel")
    @Operation(summary = "导出工程 Excel")
    @PreAuthorize("@ss.hasPermission('def:project:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportProjectExcel(@Valid ProjectPageReqVO pageReqVO,
                                   HttpServletResponse response) throws IOException {
        projectService.exportProjectExcel(pageReqVO, response);
    }


    @GetMapping("/selectInvestmentsGroupedByCity")
    @Operation(summary = "经费投入分布")
    @PermitAll
    public CommonResult<Map<String, Object>> selectInvestmentsGroupedByCity(String city) {
        return success(projectService.selectInvestmentsGroupedByCity(city));
    }
    @GetMapping("/selectProjectCountsByCityAndYear")
    @Operation(summary = "项目年增长")
    @PermitAll
    public CommonResult<List<Map<String, Object>>> selectProjectCountsByCityAndYear(String city,String xmType) {
        return success(projectService.selectProjectCountsByCityAndYear(city, xmType));
    }

    @GetMapping("/getOverallSituationNum")
    @Operation(summary = "总体情况数据格式")
    @PermitAll
    public CommonResult<List<Map<String, Object>>> getOverallSituationNum(String city) {
        return success(projectService.getOverallSituationNum(city));
    }

    @GetMapping("/selectProjectBuildingCountsByCity")
    @Operation(summary = "项目在建率")
    @PermitAll
    public CommonResult<List<Map<String, Object>>> selectProjectCountsByCity(String yearTime,String city) {
        return success(projectService.selectProjectBuildingCountsByCity(yearTime, city));
    }

    @GetMapping("/getFormattedProjectCompletionRateByCity")
    @Operation(summary = "项目完工率")
    @PermitAll
    public CommonResult<List<Map<String, Object>>> selectProjectCompletedCountsByCity(String yearTime,String city) {
        return success(projectService.getFormattedProjectCompletionRateByCity(yearTime, city));
    }


    @GetMapping("/selectProjectFundCountsByCity")
    @Operation(summary = "资金支付率,支付的除总投资")
    @PermitAll
    public CommonResult<List<Map<String, Object>>> selectProjectFundCountsByCity(String yearTime,String city) {
        return success(projectService.selectProjectFundCountsByCity(yearTime,city));
    }
    @GetMapping("/getProjectTypeNum")
    @Operation(summary = "项目类型统计")
    @PermitAll
    public CommonResult<List<Map<String, Object>>> getProjectTypeNum(String city,String xmType) {
        return success(projectService.getProjectTypeNum(city,xmType));
    }

    @GetMapping("/selectProjectsWithCategory")
    @Operation(summary = "地图点位数据")
    @PermitAll
    public CommonResult<List<Map<String, Object>>> selectProjectsWithCategory(String starTime,String endTime,String city) {
        return success(projectService.selectProjectsWithCategory(starTime,endTime,city));
    }

    @GetMapping("/getSummaryDataByCity")
    @Operation(summary = "地图点击详情")
    @PermitAll
    public CommonResult<List<Map<String, Object>>> getSummaryDataByCity(String cityName,String starTime,String endTime) {
        return success(projectService.getSummaryDataByCity(cityName,starTime,endTime));
    }

    @GetMapping("/getCity")
    @Operation(summary = "获取城市列表")
    @PermitAll
    public CommonResult<List<Map<String, String>>> getCity() {
        return success(projectService.getCity());
    }

    @GetMapping("/getCityForSearch")
    @Operation(summary = "获取城市列表")
    @PermitAll
    public CommonResult<List<Map<String, String>>> getCityForSearch() {
        return success(projectService.getCityForSearch());
    }
    @PostMapping("/import")
    @Operation(summary = "导入数据")
    @Parameters({
            @Parameter(name = "file", description = "Excel 文件", required = true)
    })
//    @PreAuthorize("@ss.hasPermission('system:user:import')")
    @PermitAll
    public CommonResult<Object> importExcel(@RequestParam("file") MultipartFile file) throws IOException {
//        Map<String, List<ProjectRespVO>> listMap = projectService.importExcel(file);
//        return success(projectService.importUserList(listMap));
        projectService.dealImportFile(file);
        return success(true);
    }


    @PostMapping("/importDevice")
    @Operation(summary = "导入数据")
    @Parameters({
            @Parameter(name = "file", description = "Excel 文件", required = true)
    })
//    @PreAuthorize("@ss.hasPermission('system:user:import')")
    @PermitAll
    public CommonResult<Object> importExcelDevice(@RequestParam("file") MultipartFile file) throws IOException {
        return success( projectService.importExcelDevice(file));
    }
    @PostMapping
    public void exportExcel(HttpServletResponse response, @RequestBody ProjectPageImportReqVO pageReqVO) throws IOException, IllegalAccessException {
        // 查询数据
        List<ProjectDO> projects = projectService.selectAll(pageReqVO);

        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=projects.xlsx");

        // 使用 EasyExcel 导出
        writeExcel(projects, pageReqVO.getFields(), response);
    }

    private void writeExcel(List<ProjectDO> projects, List<Map<String, String>> fields, HttpServletResponse response) throws IllegalAccessException {
        try {
            // 动态生成表头
            List<List<String>> headers = new ArrayList<>();
            for (Map<String, String> field : fields) {
                headers.add(Collections.singletonList(field.get("code_txt")));
            }

            // 动态生成数据
            List<List<Object>> data = new ArrayList<>();
            for (ProjectDO project : projects) {
                List<Object> row = new ArrayList<>();
                for (Map<String, String> fieldId : fields) {
                    try {
                        // 使用反射获取字段值
                        Field field = ProjectDO.class.getDeclaredField(fieldId.get("code_id"));
                        field.setAccessible(true); // 确保可以访问私有字段
                        Object value = field.get(project);

                        // 处理特殊类型（如 LocalDate）
                        if (value instanceof LocalDate) {
                            value = ((LocalDate) value).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                        }
                        row.add(value != null ? value.toString() : "");
                    } catch (NoSuchFieldException e) {
                        row.add(""); // 如果字段不存在，填充空值
                    }
                }
                data.add(row);
            }

            // 使用 EasyExcel 写入 Excel
            ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build();
            WriteSheet writeSheet = EasyExcel.writerSheet("Sheet1")
                    .head(headers)
                    .build();
            excelWriter.write(data, writeSheet);
            excelWriter.finish();

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @GetMapping("/getDeviceNum")
    @Operation(summary = "设备数量")
    @PermitAll
    public CommonResult<List<Map<String, Object>>> getDeviceNum(String xmType,String city) {
        return success(projectService.getDeviceNum(xmType,city));
    }
}